import React from 'react';
import { Table, Tag, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import useSimpleAuth from '../../hooks/useSimpleAuth';
import auth from '../../utils/auth';
import { News, PublishState } from '../../types';

// 发布状态显示配置
const publishStateLabels: Record<number, string> = {
  [PublishState.UNPUBLISHED]: '未发布',
  [PublishState.PUBLISHED]: '已发布',
  [PublishState.SUNSET]: '已下线'
};

// 发布状态颜色配置
const publishStateColors: Record<number, string> = {
  [PublishState.UNPUBLISHED]: 'default',
  [PublishState.PUBLISHED]: 'green',
  [PublishState.SUNSET]: 'red'
};

interface NewsPublishProps {
  /**
   * 新闻列表数据
   */
  dataSource: News[];
  
  /**
   * 按钮列表配置
   */
  button?: (id: number | string) => React.ReactNode;
  
  /**
   * 表格加载状态
   */
  loading?: boolean;
  
  /**
   * 是否显示发布状态列
   */
  showPublishState?: boolean;
}

/**
 * 新闻发布管理列表组件
 */
const NewsPublish: React.FC<NewsPublishProps> = ({ 
  dataSource, 
  button,
  loading = false,
  showPublishState = false
}) => {
  const navigate = useNavigate();
  const { isSuperAdmin, canAccessRegion } = useSimpleAuth();
  
  // 使用auth工具获取用户信息
  const userInfo = auth.getUserInfo() || {
    username: '未知用户',
    region: '未知区域',
    roleId: 0
  };
  
  // 获取新闻ID（兼容MongoDB的_id）
  const getNewsId = (news: News): string => {
    return String(news.seqId || news._id || news.id || '');
  };
  
  // 检查用户是否可以管理新闻
  const canManageNews = (news: News) => {
    // 超级管理员可以管理所有新闻
    if (isSuperAdmin()) {
      return true;
    }
    
    // 用户可以管理自己创建的新闻
    if (news.author === userInfo.username) {
      return true;
    }
    
    // 区域管理员可以管理本区域的新闻
    if (news.region && canAccessRegion(news.region)) {
      return true;
    }
    
    // 其他情况没有权限
    return false;
  };
  
  // 表格列定义
  const columns: ColumnsType<News> = [
    {
      title: 'ID',
      dataIndex: 'seqId',
      width: 80
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title: string, record: News) => (
        <Tooltip title="点击预览新闻详情">
          <a 
            onClick={() => navigate(`/news-manage/preview/${getNewsId(record)}`)}
            style={{ color: '#1890ff' }}
          >
            {title}
          </a>
        </Tooltip>
      )
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 120
    },
    {
      title: '所属区域',
      dataIndex: 'region',
      width: 120,
      render: (region: string) => (
        <Tag color="#108ee9">{region || '全球'}</Tag>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      width: 120,
      render: (category) => (
        <Tag color="#87d068">{category?.title || '未分类'}</Tag>
      )
    }
  ];
  
  // 如果需要显示发布状态列
  if (showPublishState) {
    columns.push({
      title: '发布状态',
      dataIndex: 'publishState',
      width: 100,
      render: (state: number) => {
        const label = publishStateLabels[state] || '未知状态';
        const color = publishStateColors[state] || 'default';
        return <Tag color={color}>{label}</Tag>;
      }
    });
  }
  
  // 添加操作列
  columns.push({
    title: '操作',
    key: 'action',
    width: 180,
    render: (_, record) => {
      // 检查用户是否有权限操作该记录
      const hasPermission = canManageNews(record);
      
      if (!hasPermission) {
        return <Tag color="red">无操作权限</Tag>;
      }
      
      return button ? button(getNewsId(record)) : null;
    }
  });
  
  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      pagination={{
        pageSize: 10,
        showTotal: (total) => `共 ${total} 条`
      }}
      rowKey={record => getNewsId(record)}
      loading={loading}
      locale={{
        emptyText: '暂无数据'
      }}
    />
  );
};

export default NewsPublish;